import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

import 'dart:math' as math;

class Coin extends StatefulWidget {
  const Coin({Key key}) : super(key: key);

  @override
  _CoinState createState() => _CoinState();
}

class _CoinState extends State<Coin> {
  VideoPlayerController _controllerFront;
  VideoPlayerController _controllerBack;

  ///显示正面
  bool _showFront;

  ///抛起
  Future<void> _drop() async {
    ///产生随机数
    final _r = math.Random().nextDouble();

    if (_r >= 0 && _r <= 0.5) {
      await _controllerFront
          .seekTo(const Duration(seconds: 0))
          .then((_) async => await _controllerFront.play());
      setState(() => _showFront = true);
    } else {
      await _controllerBack
          .seekTo(const Duration(seconds: 0))
          .then((_) async => await _controllerBack.play());
      setState(() => _showFront = false);
    }
  }

  ///播放完毕
  Future<void> _playComplate() async {
    if (_controllerFront.value.position == _controllerFront.value.duration ||
        _controllerBack.value.position == _controllerBack.value.duration) {
      await Future.delayed(
          const Duration(milliseconds: 200), () => setState(() {}));
    }
  }

  @override
  void initState() {
    super.initState();

    _showFront = true;

    _controllerFront = VideoPlayerController.asset('videos/oppo_f.mp4')
      ..initialize().then((_) => setState(() {}))
      ..addListener(_playComplate);

    _controllerBack = VideoPlayerController.asset('videos/oppo_b.mp4')
      ..initialize().then((_) => setState(() {}))
      ..addListener(_playComplate);
  }

  @override
  void dispose() {
    super.dispose();

    _controllerFront.removeListener(_playComplate);
    _controllerBack.removeListener(_playComplate);

    _controllerFront.dispose();
    _controllerBack.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Hero(
      tag: 'item2',
      child: Material(
        color: Colors.black,
        child: GestureDetector(
          onTap: _controllerFront.value.isPlaying ||
                  _controllerBack.value.isPlaying
              ? null
              : () async => await _drop(),
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              AspectRatio(
                aspectRatio: 1.08,
                child: VideoPlayer(_controllerBack),
              ),
              AnimatedOpacity(
                opacity: _showFront ? 1 : 0,
                curve: Curves.easeInExpo,
                duration: const Duration(milliseconds: 200),
                child: AspectRatio(
                  aspectRatio: 1.08,
                  child: VideoPlayer(_controllerFront),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
